layui.use(function () {
    var tree = layui.tree;
    var table = layui.table;
    var $ = layui.jquery;
    var upload = layui.upload;

    var rootDir = $("#rootDir").html();

    reloadTree(rootDir)

    upload.render({
        elem: '#btnUpload',
        url: '/localfile/upload',
        accept: 'file',
        multiple: true,
        data: {
            dir: function () {
                return $('#thisdir').text();
            }
        },
        before: function (obj) {

            if ($('#thisdir').text() === "") {
                layer.msg("请选择文件夹", {icon: 5});
                return false
            } else {
                layer.load(2);
            }
        },
        done: function (res, index, upload) {
            layer.closeAll('loading');
            if (res.code !== 200) {
                layer.msg(res.msg, {icon: 2});
            } else {
                layer.msg(res.msg, {icon: 1});
            }
            table.reloadData("ID-table-demo-data");
        },
        error: function () {
            layer.closeAll('loading');
            layer.msg('上传失败', {icon: 2});
        }
    });

    function reloadTree(rootTreeDir) {
        fetch('/localfile/directoryTreeData?dir=' + rootTreeDir)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                var result = data.data
                // 渲染
                tree.render({
                    id: "ID-tree-demo-showLine",
                    elem: '#ID-tree-demo-showLine',
                    data: result,
                    showLine: false,
                    onlyIconControl: true,
                    click: function (obj) {
                        listFile(obj);
                    },
                    edit: ['add', 'update', 'del'],
                    operate: function (obj) {
                        var type = obj.type; // 得到操作类型：add、edit、del
                        var data = obj.data; // 得到当前节点的数据
                        var elem = obj.elem; // 得到当前节点元素

                        if (data.isRoot && type != 'add') {
                            layer.msg("此文件夹禁止操作", {icon: 5, time: 500});
                            reloadTree(rootDir);
                            return;
                        }


                        var id = data.id; // 得到节点索引
                        if (type === 'add') { // 增加节点
                            layer.prompt({title: '创建文件夹', formType: 0}, function (pass, index) {
                                layer.close(index);

                                $.post('/localfile/add', {
                                    fileName: pass,
                                    dir: id,
                                    isDirectory: true
                                }, function (res) {
                                    if (200 === res.code) {
                                        reloadTree(rootDir)
                                        layer.msg('创建文件夹成功', {icon: 1});
                                    } else {
                                        layer.msg(res.msg, {icon: 5, time: 500});
                                    }
                                }, 'JSON');
                                return pass;
                            });

                        } else if (type === 'update') { // 修改节点
                            rename(obj.data.id, elem.find('.layui-tree-txt').html())
                        } else if (type === 'del') { // 删除节点
                            deleteDir(obj.data.id)
                        }

                        reloadTree(rootDir)
                    }
                });
            })
    }

    function listFile(obj) {

        $("#thisdir").html(obj.data.id)

        // 已知数据渲染
        table.render({
            id: "ID-table-demo-data",
            elem: '#ID-table-demo-data',
            url: '/localfile/list?filePath=' + obj.data.id + "&fileName=",
            cols: [[ //标题栏
                {field: 'fileName', title: '文件名', minWidth: 200},
                {
                    field: 'fileSize', title: '大小', width: 120, templet: function (d) {
                        return d.isDirectory ? "" : formatFileSize(d.fileSize)
                    }
                },
                {field: 'modifyTime', title: '最后修改时间', width: 180},
                {field: 'city', title: '操作', width: 190, toolbar: '#barDemo'},
            ]],
            height: '540px',
            //skin: 'line', // 表格风格
            //even: true,
            page: false, // 是否显示分页
            parseData: function (res) { // res 即为原始返回的数据
                return {
                    "code": res.code === 200 ? 0 : res.code, // 解析接口状态
                    "msg": res.msg, // 解析提示文本
                    "data": res.data // 解析数据列表
                };
            },
            done: function () {
                table.on('tool(test)', function (obj) {
                    if (obj.event === 'open') {
                        const loadUrl = window.location.origin;
                        if (obj.data.isDirectory) {
                            layer.msg("当前为文件夹, 无法打开/下载", {icon: 5, time: 1000});
                        } else {
                            window.open(loadUrl + obj.data.preview)
                        }
                    } else if (obj.event === 'rename') {
                        layer.prompt({title: '重命名', formType: 0}, function (pass, index) {
                            rename(obj.data.filePath, pass, 'file')
                            layer.close(index);
                        });
                    } else if (obj.event === 'delete') {
                        layer.confirm('确定删除文件？', {
                            btn: ['确定', '关闭'] //按钮
                        }, function () {

                            deleteDir(obj.data.filePath)

                        }, function () {

                        });
                    }
                });
            }
        });
    }

    function deleteDir(filePath) {
        var requestData = JSON.stringify([{filePath: filePath}]);

        $.ajax({
            url: '/localfile/delete',
            type: 'POST',
            contentType: 'application/json', // 设置Content-Type为application/json
            data: requestData,
            dataType: 'json',
            success: function (res) {
                if (res.code === 200) {
                    reloadTree(rootDir);
                    table.reloadData("ID-table-demo-data");
                    layer.msg('删除成功', {icon: 1});
                } else {
                    layer.msg(res.msg, {icon: 5, time: 500});
                }
            },
            error: function (xhr, status, error) {
                // 处理错误
                console.error(error);
            }
        });
    }

    function rename(filePath, rename, type) {

        $.post('/localfile/rename', {
            filePath: filePath,
            rename: rename
        }, function (res) {
            if (res.code === 200) {
                layer.msg('修改成功', {icon: 1});

                if (type === "file") {
                    table.reloadData("ID-table-demo-data")
                } else {
                    reloadTree(rootDir)
                }

            } else {
                layer.msg(res.msg, {icon: 5, time: 500});
            }
        }, 'JSON');
    }

    function formatFileSize(fileSizeInBytes) {
        // 将字节数转换为KB
        const fileSizeInKB = fileSizeInBytes / 1024;

        // 如果文件大小大于1GB，则转换为GB，否则如果大于1MB，转换为MB，否则保留小数点后两位并添加KB单位
        if (fileSizeInKB >= 1024) {
            const fileSizeInMB = fileSizeInKB / 1024;
            if (fileSizeInMB >= 1024) {
                const fileSizeInGB = fileSizeInMB / 1024;
                return fileSizeInGB.toFixed(2) + ' GB';
            } else {
                return fileSizeInMB.toFixed(2) + ' MB';
            }
        } else {
            return fileSizeInKB.toFixed(2) + ' KB';
        }
    }


});